package com.bootdo.market.controller;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.OssConstant;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.market.common.HistoryTodayRedis;
import com.bootdo.market.dao.CommonDao;
import com.bootdo.market.dao.DuplicateDao;
import com.bootdo.market.domain.ProductArticleDO;
import com.bootdo.market.domain.ProductCatalogDO;
import com.bootdo.market.domain.StickypostsCalalogArticleDO;
import com.bootdo.market.service.ProductArticleService;
import com.bootdo.market.service.ProductCatalogService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jinse
 * @email market@jinse.com
 * @date 2019-07-09 14:41:39
 */

@Controller
@RequestMapping("/market/productCatalog")
public class ProductCatalogController {
    @Autowired
    private ProductCatalogService productCatalogService;
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private DuplicateDao duplicateDao;
    @Autowired
    private HistoryTodayRedis historyTodayRedis;
    @Autowired
    private ProductArticleService productArticleService;

    @GetMapping()
    @RequiresPermissions("market:productCatalog:productCatalog")
    String ProductCatalog() {
        return "market/productCatalog/productCatalog";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("market:productCatalog:productCatalog")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ProductCatalogDO> productCatalogList = productCatalogService.list(query);
        productCatalogList.stream().forEach(productCatalogDO -> {
            productCatalogDO.setTagname(commonDao.findProductCatalogTagNamesByCatalogId(productCatalogDO.getId()));
        });
        int total = productCatalogService.count(query);
        PageUtils pageUtils = new PageUtils(productCatalogList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("market:productCatalog:add")
    String add() {
        return "market/productCatalog/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("market:productCatalog:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        ProductCatalogDO productCatalog = productCatalogService.get(id);
        String s = commonDao.findProductCatalogTagsByCatalogId(id);
        if (s != null && !"".equals(s)) {
            productCatalog.setTagid(s);
        }
        model.addAttribute("productCatalog", productCatalog);
        return "market/productCatalog/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("market:productCatalog:add")
    public R save(ProductCatalogDO productCatalog) {
        if (productCatalogService.save(productCatalog) > 0) {
            productCatalogService.saveProductCatalogTags(productCatalog);
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("market:productCatalog:edit")
    public R update(ProductCatalogDO productCatalog) {
        //todo 先删除redis的这个zset的sort，因为sort会改变
        ProductCatalogDO aaaa = productCatalogService.get(productCatalog.getId());
        historyTodayRedis.deleteProductCatalogRedis(aaaa);

        productCatalogService.update(productCatalog);
        if (productCatalogService.delProductCatalogTags(productCatalog) > 0) {
            productCatalogService.saveProductCatalogTags(productCatalog);
        }
        ProductCatalogDO bbbb = productCatalogService.get(productCatalog.getId());
        updateDataIntoRedis(bbbb);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("market:productCatalog:remove")
    public R remove(ProductCatalogDO productCatalog) {
        productCatalogService.update(productCatalog);
        ProductCatalogDO bbbb = productCatalogService.get(productCatalog.getId());
        updateDataIntoRedis(bbbb);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("market:productCatalog:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            ProductCatalogDO productCatalogDO = new ProductCatalogDO();
            productCatalogDO.setId(ids[i]);
            productCatalogDO.setCatalogonlinestate(1);
            productCatalogService.update(productCatalogDO);
            ProductCatalogDO bbbb = productCatalogService.get(productCatalogDO.getId());
            updateDataIntoRedis(bbbb);
        }
        return R.ok();
    }

    @RequestMapping(value = "/listAllTags", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String listAllTags(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        List<Map<String, Object>> list = commonDao.listAllTags(params);

        return JSON.toJSONString(list);
    }

    @RequestMapping(value = "/productCatalogUniqueAdd", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R productCatalogUniqueAdd(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        Map<String, Object> aa = duplicateDao.productCatalogUniqueAdd(params);
        Map<String, Object> bb = duplicateDao.productCatalogUniqueAddAdd(params);
        if (aa == null && bb == null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping(value = "/productCatalogUniqueEdit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public R productCatalogUniqueEdit(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        Map<String, Object> aa = duplicateDao.productCatalogUniqueEdit(params);
        Map<String, Object> bb = duplicateDao.productCatalogUniqueEditEdit(params);
        if (aa == null && bb == null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping(value = "/listAllCatalogs", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String listAllCatalogs(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        List<Map<String, Object>> list = commonDao.listAllCatalogs(params);

        return JSON.toJSONString(list);
    }

    /**
     * 将频道信息更新进入redis
     */
    void updateDataIntoRedis(ProductCatalogDO aaaa) {
        if (aaaa.getCatalogstate() == 1 && aaaa.getCatalogonlinestate() == 1) {
            historyTodayRedis.saveProductCatalogRedis(aaaa);
        } else {
            historyTodayRedis.deleteProductCatalogRedis(aaaa);
        }
    }

    @GetMapping("/catalogArticle")
    @RequiresPermissions("market:productCatalog:catalogArticle")
    String catalogArticle(Integer catalogid, Model model) {
        model.addAttribute("catalogid", catalogid);
        return "market/productCatalog/productCatalogArticle";
    }

    @ResponseBody
    @GetMapping("/catalogArticleList")
    @RequiresPermissions("market:productCatalog:catalogArticleList")
    public PageUtils catalogArticleList(@RequestParam Map<String, Object> params) {

        //查询列表数据
        Query query = new Query(params);
        List<ProductArticleDO> productCatalogList = productCatalogService.catalogArticleList(query);
        if (productCatalogList.size() > 0) {
            productCatalogList.forEach(item -> {
                if (item.getArticlecoverurl() != null && !"".equals(item.getArticlecoverurl())) {
                    item.setArticlecoverurl("http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + item.getArticlecoverurl());
                }
                Map<String, Object> map = new HashMap<>();
                map.put("catalogId", params.get("catalogid"));
                map.put("articleId", item.getId());
                Map<String, Object> maps = commonDao.getStickypostsarticle(map);
                if (maps == null) {
                    item.setStickyPostsState(0);
                } else {
                    item.setStickyPostsState(1);
                }
            });
        }
        int total = productCatalogService.catalogArticleListCount(query);
        PageUtils pageUtils = new PageUtils(productCatalogList, total);
        return pageUtils;
    }

    /**
     * 置顶
     */
    @Transactional
    @PostMapping("/stickyPosts")
    @ResponseBody
    @RequiresPermissions("market:productCatalog:stickyPosts")
    public R stickyPosts(StickypostsCalalogArticleDO stickypostsCalalogArticleDO) {
        ProductArticleDO aaa = productArticleService.get(stickypostsCalalogArticleDO.getArticleid());
        stickypostsCalalogArticleDO.setStickypostsmonthday(aaa.getArticlehistorymonthday());
        aaa.setCatalogid(stickypostsCalalogArticleDO.getCatalogid());
        commonDao.deleteProductStickypostsCalalogArticle(stickypostsCalalogArticleDO);
        historyTodayRedis.deleteStickypostsRedis(aaa);
        if (stickypostsCalalogArticleDO.getStickyPostsState() == 1) {
            commonDao.insertProductStickypostsCalalogArticle(stickypostsCalalogArticleDO);
            historyTodayRedis.saveStickypostsRedis(aaa);
        }
        return R.ok();
    }


}
